/**
   功能：
   1.将客户端发来的数据转发到串口；
   2.串口数据转发给所有客户端
   3.可连接4个客户端
   4.可设置静态IP地址
   5.指示灯闪烁表示无客户端连接，灯亮代表有客户端连接
*/

#include <ESP8266WiFi.h>

//定义最多多少个client可以连接本server
#define MAX_SRV_CLIENTS 4

//路由器WIFI和密码
const char* ssid = "wifi_name";
const char* password = "88888888";

//静态地址、网关、子网掩码
IPAddress local_IP(192, 168, 0, 200);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);

//创建server
WiFiServer server(8088);//端口号，随意修改，范围0-65535
//管理clients
WiFiClient serverClients[MAX_SRV_CLIENTS];

int a = 0; //连接状态标识
int i = 0;//用于for循环

void setup() {
  //波特率
  Serial.begin(9600);
  //连接WIFI
  MyconnectWIFI();
  //启动server
  server.begin();

  //定义输入引脚  （此程序并没有用到，放到这里方便大家使用）
  pinMode(16, INPUT);//   D0
  pinMode(5, INPUT);//    D1
  pinMode(4, INPUT);//    D2
  pinMode(0, INPUT);//    D3

  //定义输出引脚
  pinMode(2, OUTPUT);//     D4
  pinMode(14, OUTPUT);//    D5
  pinMode(12, OUTPUT);//    D6
  pinMode(13, OUTPUT);//    D7
  pinMode(15, OUTPUT);//    D8

  digitalWrite(2, LOW);//输出低电平
  digitalWrite(14, HIGH);//输出高电平
}

void loop() {
  //检测新的Client
  NewClient();
  
  //LED指示灯
  LEDstate();
  
  //把收到的客户端数据发送到串口
  ReceiveData();
  
  //串口数据发送到客户端
  SendData();
}

//连接WIFI
void MyconnectWIFI() {

  WiFi.config(local_IP, gateway, subnet);//设置静态IP
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);//路由器的WiFi名称和密码
  //  Serial.print("\nConnecting to ");
  //  Serial.println(ssid);
  
  //等待连接
  while (WiFi.status() != WL_CONNECTED && i++ < 200) {
    delay(500);
    Serial.print(".");
  }
  
  if (i == 201) {
  
    //    Serial.print("\nCould not connect to ");
    //    Serial.println(ssid);
    while (1) {
    }
    
  } else {
    //    Serial.print("\nReady! Use 'telnet ");
    //    Serial.print(WiFi.localIP());
    //    Serial.println(" 8088' to connect");
  }
}

//有客户端连接时常亮，无连接时闪烁
void LEDstate() {
  //连接情况 用led灯的状态显示
  a = 0;
  for (int i = 0; serverClients[i].connected(); i++) {
    a = 1;
  }
  if (a == 0) {
    digitalWrite(2, HIGH);
    delay(500);
    digitalWrite(2, LOW);
    delay(500);
    //    Serial.println("no");
  } else {
    digitalWrite(2, LOW);
  }
}

//检测新的client
void NewClient() {
  //检测是否有新的client请求进来
  if (server.hasClient()) {
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      //释放旧无效或者断开的client
      if (!serverClients[i] || !serverClients[i].connected()) {
        if (serverClients[i]) {
          serverClients[i].stop();
        }
        //分配最新的client
        serverClients[i] = server.available();
        //Serial.print("New client: ");
        //Serial.print(i);
        break;
      }
    }
    //当达到最大连接数 无法释放无效的client，需要拒绝连接
    if (i == MAX_SRV_CLIENTS) {
      WiFiClient serverClient = server.available();
      serverClient.stop();
      //      Serial.println("Connection rejected ");
    }
  }
}

//把收到的客户端数据发送到串口
void ReceiveData() {
  for (i = 0; i < MAX_SRV_CLIENTS; i++) {
    if (serverClients[i] && serverClients[i].connected()) {
      while (serverClients[i].available())
      {
        uint8_t data = serverClients[i].read();
        Serial.println(data);
      }
    }
  }
}

//把串口数据发送到客户端
void SendData() {
  if (Serial.available()) {   //串口读取到的转发到wifi，因为串口是一位一位的发送所以在这里缓存完再发送
    size_t counti = Serial.available();
    uint8_t sbuf[counti];
    Serial.readBytes(sbuf, counti);
    //Serial.write(sbuf, counti);
    //将数据发送给客户端
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      if (serverClients[i] && serverClients[i].connected()) {
        serverClients[i].write(sbuf, counti);
        delay(200);
      }
    }
  } else {
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      //释放旧无效或者断开的client
      if (serverClients[i].connected()) {
        //serverClients[i].println("not data");
        delay(500);
      }
    }
  }
}
